<?php
namespace pad;
use control\machiningOrderClass;
/*
*报工端-生产派工类
*/

class dispatchClass extends indexClass
{
    private const page = 'machiningSendOrder';
    private const table = 'machining_send_order';
    private const title = '生产派工';
    private const type = 'dispatch';

    /*列表-查询条件*/
    /**
     * 生产派工
     */
    public function home()
    {
        if(!isset($_SESSION[self::type]['search_text']))$this->conditions();
        $choiceBlock = $this->choiceBlock();
        $condition = $_SESSION[self::type]['condition_arr'];
        //全等查询数组
        $equal = array(
            'a.coid' => self::$coid,
            'b.isClose'=>0,
            'b.state'=>'已确认',
        );
        //like查询数组
        $like = array(
        );
        $where = search(array("like" => $like, "=" => $equal));
        //根据查询条件生成sql
        foreach ((array)$condition as $key=>$value){
            switch ($key)
            {
                case "date":
                    foreach ((array)$value as $val){
                        $where .= $this->getTimePeriod($val,'date','b.startDate');
                    }
                    break;
                case "state":
                    foreach ((array)$value as $val){
                        $where .= match ($val) {
                            '待派工' => " and a.id not in (select distinct machiningOrderMxId from machining_send_order where coid = '".self::$coid."' and processId = rd.processId) ",
                            '部分派工' => " and (select ifnull(sum(num),0) from machining_send_order where coid = '".self::$coid."' and machiningOrderMxId = a.id and processId = rd.processId) > 0 and (select ifnull(sum(num),0) from machining_send_order where coid = '".self::$coid."' and machiningOrderMxId = a.id and processId = rd.processId) < a.num",
                            '已派工' => " and (select ifnull(sum(num),0) from machining_send_order where coid = '".self::$coid."' and machiningOrderMxId = a.id and processId = rd.processId) >= a.num",
                            default=>'',
                        };
                    }
                    break;
                case "type":
                    $where .= " and b.type in ('".implode("','",$value)."') ";
                    break;
                case "product_line":
                    $where .= " and b.lineId in ('".implode("','",$value)."') ";
                    break;
                default:
                    $where .= "";
            }
        }
        if(isset($_SESSION[self::type]['orderNo'])){
            $where .= " and b.orderNo like '%".$_SESSION[self::type]['orderNo']."%' ";
        }
        $result = find(array(
            "table" => "machining_order_mx as a join machining_order as b on a.orderId = b.id right join routing_detail as rd on rd.orderId = a.routingId",
            "field" => " a.*,b.orderNo,b.lineId,b.type,b.startDate,b.endDate,rd.processId ",
            "where" => " 1=1 {$where} order by b.recordDate desc,a.`list` asc "
        ));
        $ul = "";
        if(is_array($result['array'])){
            foreach ($result['array'] as $array){
                $line = query('product_line', "id = '$array[lineId]'");
                $material = query('material', "id = '$array[materialId]'","name,code,model,unit");
                $process = query('process', "id = '$array[processId]'","id,name");
                $assigned = find(array("table"=>"machining_send_order","field"=>" ifnull(sum(num),0) as num ","single"=>" coid = '".self::$coid."' and machiningOrderMxId = '".$array['id']."' and processId = '".$array['processId']."' "))['num']?:0;
                $name = $material['code'].','.
                    $material['name'].','.
                    $material['model'];
                $ul .= "<ul data-id='{$array['id']}' onclick=\"sureChoice('{$array['id']}','{$process['id']}')\">
                    <li>{$array['orderNo']}</li>
                    <li>{$name}</li>
                    <li>".$line['workshop'] . '-' . $line['name']."</li>
                    <li>{$process['name']}</li>
                    <li>".self::lostZero($array['num'],'numPrecision')."</li>
                    <li>".self::lostZero($assigned,'numPrecision')."</li>
                    <li>{$array['startDate']}</li>
                    <li>{$array['endDate']}</li>
                </ul>";
            }
        }
        $orderNo = isset($_SESSION[self::type]['orderNo'])?$_SESSION[self::type]['orderNo']:'';
        //生成页面
        $html = $this->commonHead('生产派工')."
		<div class='center'>
           <div class='search'>
                <div class='flex-div'>
                    <p class='search-left'>
                       <span class='search-title'>计划单</span>
                       <span style='position: relative'>
                            <input type='text' name='orderNo' autocomplete='off' id='orderCode' placeholder='输入' title='输入' class='text' value='".$orderNo."' onblur=\"searchFormRender('dispatch')\">
                            <!--<img onclick=\"layer('moveStock','choiceLocation')\" class='search-scan' src='".root."img/control/scan.svg'>-->
                        </span>
                    </p>
                    <p>
                        <span>筛选条件：</span>
                        <span>".$_SESSION[self::type]['search_text']."</span>
                    </p>
                </div>
                <div class='search-right'><img onclick=\"animatedOperation('choice-block','right','show')\" src='".root."img/control/detail.svg' alt=''></div>
            </div>
           <div class='content'>
                <ul>
                    <li>源单号</li>
                    <li>产品信息</li>
                    <li>生产线</li>
                    <li>工序</li>
                    <li>计划数量</li>
                    <li>已派工数量</li>
                    <li>计划开始时间</li>
                    <li>计划完工时间</li>
                </ul>
                {$ul}
            </div>
		</div>
		<div class='footer'>
                <p>
                    <input type='hidden' name='choiceId' value=''>
                    <input type='hidden' name='processId' value=''>
                    <button type='button' class='newButton' onClick=\"dispatch()\">派工</button>
                </p>
		</div>".$this->commonNavigation('生产派工').$choiceBlock;
        $js   = "
        <script>
        function sureChoice(id,processId){
            $(\"[name='choiceId']\").val(id)
            $(\"[name='processId']\").val(processId)
        }
        function dispatch(){
            var id = $(\"[name='choiceId']\").val()
            var processId = $(\"[name='processId']\").val()
            if (!id){
                msg('请先选择计划单，再进行派工','error');
            }else{
                window.location.href = root+'pad/index.html?cla=dispatch&fun=dispatchDetail&orderMxId='+id+'&processId='+processId;
            }
        }
        $(function(){
            
        })
        </script>".$this->jsReport();
        return head("report") . $html . $js . warn() . "\n</body>\n</html>";
    }
    /*******生产派工-存储筛选条件到SESSION*******/
    public function conditions(){
        $product_line = find(array("table" => "product_line", "field" => "concat(workshop,'-',name) as name,id", "where" => " coid = '".self::$coid."' and state = '启用' "));
        $line_arr = !empty($product_line['array'])?array_column($product_line['array'], 'name', 'id'):[];
        //筛选数据
        $data = array(
            array(
                "text"=>"开工日期",
                "name"=>"date",
                "type"=>"radio",
                "value"=>['今天','昨天','近三天','本周','本月'],
            ),
            array(
                "text"=>"状态",
                "name"=>"state",
                "type"=>"radio",
                "value"=>['待派工','部分派工','已派工'],
            ),
            array(
                "text"=>"加工类型",
                "name"=>"type",
                "type"=>"checkbox",
                "value"=>['生产加工', '生产返工'],
            ),
            array(
                "text"=>"生产线",
                "name"=>"product_line",
                "type"=>"checkbox",
                "value"=>$line_arr,
            ),
        );
        $type = self::type; //类型派工
        //组成新的数据存为session
        $arr = [];
        $text = [];
        $conditionArr = [];
        foreach ($data as $array){
            switch ($array['type'])
            {
                case "radio":
                    $choice = $this->post($array['name']) ?[$this->post($array['name'])]: [];
                    break;
                default:
                    $choice = $this->post($array['name']) ?: [];
            }
            $value = [];
            //如果用此数组中所有的值组成的数组完全等于此数组，则说明此数组为索引数组，反之为关联数组
            if (array_values($array['value']) === $array['value']) {
                foreach ((array)$array['value'] as $item) {
                    $checked = in_array($item, $choice);
                    if ($checked) {
                        $text[] = $item;
                        if (isset($conditionArr[$array['name']])) {
                            $conditionArr[$array['name']][] = $item;
                        } else {
                            $conditionArr[$array['name']] = [$item];
                        }
                    }
                    $value[] = [
                        'name' => $item,
                        'checked' => $checked,
                    ];
                }
            }else{
                foreach ((array)$array['value'] as $key => $item) {
                    $checked = in_array($key, $choice);
                    if ($checked) {
                        $text[] = $item;
                        if (isset($conditionArr[$array['name']])) {
                            $conditionArr[$array['name']][] = $key;
                        } else {
                            $conditionArr[$array['name']] = [$key];
                        }
                    }
                    $value[$key] = [
                        'name' => $item,
                        'checked' => $checked,
                    ];
                }
            }
            $array['value'] = $value;
            $arr[] = $array;
        }
        //重置则恢复默认
        if(empty($text)){
            $arr[0]['value'][0]['checked'] = true;
            $arr[1]['value'][0]['checked'] = true;
            $conditionArr['date'] = ['今天'];
            $conditionArr['state'] = ['待派工'];
            $text[] = '今天';
            $text[] = '待派工';
        }
        $_SESSION[$type]['search'] = $arr;
        $_SESSION[$type]['orderNo'] = $this->post('orderNo');
        $_SESSION[$type]['search_text'] = implode('，',$text);
        $_SESSION[$type]['condition_arr'] = $conditionArr;
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /*班组查询-查询结果*/
    public function getTeam($teamId='')
    {
        //like查询数组
        $like = array(
        );
        //全等查询数组
        $equal = array(
        );
        $and = " and state ='启用' and coid = '" . self::$coid . "' ";
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;

        $page = $this->pageSmall(array("table" => "team","fun" => "getTeam",
            'field'=>"name,id", "where" => $where, "order" => "time desc"));
        //获取表头
        $tr = "";
        $teamName = "";
        //获取记录
        if(is_array($page['array'])) {
            if(!$teamId) {
                $teamId = $page['array'][0]['id'];
            }
            $result = array_chunk($page['array'],2);
            foreach ($result as $res) {
                $td = "";
                foreach ((array)$res as $array){
                    $class = $array['id']==$teamId?'choice-font':'';
                    $teamName = $array['id']==$teamId?$array['name']:$teamName;
                    $td .= "<td data-id='{$array['id']}' data-name='{$array['name']}' class='team-item $class'>{$array['name']}</td>";
                }
                $tr .= "<tr>$td</tr>";
            }
        }
        //返回
        $json['html'] = "<p class='partition-title'>班组：<span id='teamName'>$teamName</span></p>
                            <div class='team'>
                                <table class='table-small'>
                                    $tr
                                </table>
                            </div>
                            ".$page['button'].hidden(array("name"=>"teamId","value"=>$teamId));
        return json_encode($json, 320);
    }

    /**
     * 派工详情
     */
    public function dispatchDetail()
    {
        $id = $this->get('id')?:'';
        $machining_send_order = query("machining_send_order"," id = '$id' ");
        $orderMxId = $machining_send_order['machiningOrderMxId']?:$this->get('orderMxId');
        $machining_order_mx = query("machining_order_mx"," id = '$orderMxId' ");
        $machining_order = query("machining_order"," id = '$machining_order_mx[orderId]' ");
        $line = query('product_line', "id = '$machining_order[lineId]'");
        $material = query('material', "id = '$machining_order_mx[materialId]'");

        $processName = "";
        $processId = $machining_send_order['processId']?:$this->get('processId');
        $assigned = find(array("table"=>"machining_send_order","field"=>" ifnull(sum(num),0) as num ","single"=>" coid = '".self::$coid."' and machiningOrderMxId = '".$machining_order_mx['id']."' and processId = '$processId'"))['num']?:0;
        $name = $material['code'].','.
            $material['name'].','.
            $material['model'];
        $unassigned = (float)$machining_order_mx['num'] - (float)$assigned ;
        $machining_send_order['num'] = $machining_send_order['id']?$machining_send_order['num']:($unassigned<0?0:$unassigned);
        //数字键盘
        $tr = "<tr>";
        for ($i = 1; $i < 10; $i++) {
            $tr .= "<td class='key-item' data-num='$i' data-name='num'>$i</td>";
            if($i%3==0){
                $tr .= "</tr><tr>";
            }
        }
        $calculator = "<div class='calculator'>
                            <table class='table-calculator'>
                                $tr
                                <tr>
                                    <td class='key-item' data-num='0' data-name='num'>0</td>
                                    <td class='key-item spot' data-num='spot' data-name='num'>.</td>
                                    <td class='key-item delete' data-num='delete' data-name='num'><img src='".root."img/control/calculator_del.svg' alt=''></td>
                                </tr>
                            </table>
                        </div>";
        //工序
        $processResult = find(array("table"=>"process","field"=>"name,id","where"=>" state ='启用' and coid = '".self::$coid."' and id in (select processId from routing_detail where orderId = '$machining_order_mx[routingId]') "));
        $tr = "";
        if(is_array($processResult['array'])){
            if(!$processId) {
                $processId = $processResult['array'][0]['id'];
            }
            //数组分段
            $arr = array_chunk($processResult['array'],2);
            foreach ($arr as $result) {
                $td = "";
                foreach ($result as $array) {
                    $class = $array['id']==$processId?'choice-font':'';
                    $processName = $array['id']==$processId?$array['name']:$processName;
                    $td .= "<td data-id='{$array['id']}' data-name='{$array['name']}' class='process-item $class'>{$array['name']}</td>";
                }
                $tr .= "<tr>$td</tr>";
            }
        }
        $process = "<p class='partition-title'>工序：<span id='processName'>$processName</span></p>
                        <div class='process'>
                            <table class='table-small'>
                                {$tr}
                            </table>
                        </div>".hidden(array("name"=>"processId","value"=>$processId));
        //班组
        $teamJson = $this->getTeam($machining_send_order['teamId']);
        $teamArr = json_decode($teamJson,true);
        //生成页面
        $html = $this->commonHead('生产派工')."
		<div class='center'>
           <div class='onion'>
                <div class='back-but'><img onclick=\"window.location.href=root+'pad/index.html?cla=dispatch&fun=home'\" src='".root."img/control/return.svg' alt=''></div>
                <div class='flex-div onion-text'>
                    <p>
                        <span>派工单</span>
                        <span></span>
                    </p>
                </div>
            </div>
           <div class='center'>
                <form name='editForm'>
                    <div class='center-text'>
                        <ul>
                            <li>源单类型：{$machining_order['orderType']}</li>
                            <li>源单号：{$machining_order['orderNo']}</li>
                            <li>加工类型：{$machining_order['type']}</li>
                            <li>生产线：".$line['workshop'] . '-' . $line['name']."</li>
                        </ul>
                        <ul>
                            <li>物料：{$name}</li>
                            <li>源单数量：".self::lostZero($machining_order_mx['num'],'numPrecision')." {$machining_order_mx['unit']}</li>
                            <li>已派工：".self::lostZero($assigned,'numPrecision')." {$machining_order_mx['unit']}</li>
                            <li>待派工：{$unassigned} {$machining_order_mx['unit']}</li>
                        </ul>
                    </div>
                    <div class='center-operation'>
                        <div class='operation-partition'>
                            {$process}
                        </div>
                        <div class='operation-partition' id='getTeamHtml'>
                            {$teamArr['html']}
                        </div>
                        <div class='operation-partition '>
                            <p class='partition-title'>计划产量：<span>".text(array("name"=>"num","other"=>self::digitalFiltering('numPrecision'),"class"=>"text width100","value"=>self::lostZero($machining_send_order['num'],'numPrecision')))."</span></p>
                            {$calculator}
                        </div>
                        <div class='operation-partition border-r'>
                            <p class='m-b-30'><span class='head-span'>开始时间：</span><span class='head-input-span'>".text(array("name"=>"startDate","class"=>"input","laydate"=>[],"other"=>"readonly","value"=>$machining_send_order['startDate']))."</span></p>
                            <p class='m-b-30'><span class='head-span'>结束时间：</span><span class='head-input-span'>".text(array("name"=>"endDate","class"=>"input","laydate"=>[],"other"=>"readonly","value"=>$machining_send_order['endDate']))."</span></p>
                            <p class='remark-p'><span class='head-span'>备注：</span><span class='head-input-span'>".textarea(array("name"=>"text","class"=>"input remark","value"=>$machining_send_order['text']))."</span></p>
                        </div>
                    </div>
                    ".hidden(array('name' => 'machiningOrderMxId', 'value' => $machining_order_mx['id'])).hidden(array('name' => 'id', 'value' => $id))."
                </form>
            </div>
		</div>
		<div class='footer-two'>
           <p>
                    <button type='button' class='newButton-left' onClick=\"subForm('editForm',root+'pad/index.html?cla=dispatch&fun=editEdit')\">保存</button>
                    <button type='button' class='newButton' onClick=\"subForm('editForm',root+'pad/index.html?cla=dispatch&fun=editEdit&sign=post')\">提交</button>
                </p>
		</div>
        ".$this->commonNavigation('生产派工');
        $js   = "
        <script>
        $(function(){
            
        })
        </script>".$this->jsReport();
        return head("report") . $html . $js . warn() . "\n</body>\n</html>";
    }

    /*编辑*/
    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $state = $this->get('sign')=='post'?'待确认':'草稿';
        //赋值
        $field = array(

            "startDate" => $this->post('startDate'),
            "endDate" => $this->post('endDate'),
            "machiningOrderMxId" => $this->post('machiningOrderMxId'),//备注
            "processId" => $this->post('processId'),
            "num" => $this->post('num'),
            'teamId'=>$this->post('teamId'),
            "text" => $this->post('text'),
            'state' => $state
        );
        $annotation = [
            "machiningOrderMxId" => '生产计划',
            "processId" => '工序',
            "num" => '生产数量',
        ];
        $rules = [
            "machiningOrderMxId" => 'required',
            "processId" => 'required',
            "num" => 'required|numeric',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query('machining_send_order', " id = '" . $id . "' ");
        //判断
        if (!$this->power('machiningSendOrder', "edit")) {
            $json['warn'] = "权限不足";
        } elseif ($info['state'] == '已确认') {
            $json['warn'] = '此生产派工单已确认，不能编辑';
        } elseif (!empty($field['startDate']) && !empty($field['endDate']) && strtotime($field['endDate']) < strtotime($field['startDate'])) {
            $json['warn'] = '计划完工时间不能小于计划开工时间';
        } else {
            $json['warn']='';
            $machiningOrderMx = query('machining_order_mx', "id = '$field[machiningOrderMxId]'");
            $machiningOrder = query('machining_order', "id = '$machiningOrderMx[orderId]'");
            $occupyNum = $this->judgeExceedNum($machiningOrderMx['id'],$id,$field['processId'],$machiningOrderMx['unit']);
            if (!self::getSettingItem('生产','allowMoreProcessNum') && $machiningOrderMx['num'] < round($occupyNum+$field['num'],2)){
                $json['warn'] = "派工数量已超过此加工单数量";
            }
            if (empty($json['warn'])){
                $field['type'] = $machiningOrder['type'];
                $field['unit'] = $machiningOrderMx['unit'];
                $field['lineId'] = $machiningOrder['lineId'];
                $field['orderType'] = $machiningOrder['orderType'];
                $field['machiningOrderId'] = $machiningOrder['id'];
                $field['materialId'] = $machiningOrderMx['materialId'];
                $field['routingId'] = $machiningOrderMx['routingId'];
                $routingDetail = query('routing_detail',"orderId = '$field[routingId]' and processId ='$field[processId]' order by list");
                $field['classify'] = $routingDetail['isOut']=='是'?'委外派工':'生产派工';
                $field['routingMxId'] = $routingDetail['id'];
                if (empty($info['id'])) {
                    $userNo = self::generateCode('machiningSendOrder',[
                        'prefix' => 'SCPG' . date('Ymd'),
                        'table' => 'machining_send_order',
                        'field' => 'orderNo',
                        'where' => " and coid = '".self::$coid."'",
                    ],$field);
                    $field = array_merge($field, array("id" => $id, 'recordDate'=>$this->date, 'coid' => self::$coid, 'orderNo' => $userNo, 'stid' => $this->control['stid']));
                    $json['warn'] = insert(array("table" => 'machining_send_order', "field" => $field));
                } else {
                    $json['warn'] = update(array("table" => 'machining_send_order', "field" => $field, "where" => "id = '$info[id]'"));
                }
                if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                    if ($json['warn'] == '新增成功') {
                        self::operateRecord($id,'生产派工单','新增');
                    }
                    if($this->get('sign')=='post')self::operateRecord($id,'生产派工单','提交');
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了生产派工单ID：" . $id;
                    $this->logText(array("type" => 'machiningSendOrder', "text" => $text));
                    //返回
                    $_SESSION['warn'] = '操作成功';
                    $json['warn'] = 2;
                }
            }
        }

        $json['id'] = $id;
        if($this->get('sign')=='post') {
            $json['href'] = root . "pad/index.html?cla=dispatch&fun=home";
        }else{
            $json['href'] = root . "pad/index.html?cla=dispatch&fun=dispatchDetail&id=".$id;
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 获取已派工的生产数量
     * @param $machiningOrderMxId
     * @param $id
     * @param $processId
     * @param $unit
     * @return float|int
     */
    public function judgeExceedNum($machiningOrderMxId,$id,$processId,$unit){
        $all = find(array('table'=>'machining_send_order',"where"=>"coid = '".self::$coid."' and id !='$id' and processId = '$processId' and machiningOrderMxId = '$machiningOrderMxId'"));
        $num = 0;
        foreach ($all['array'] as $array){
            $num+=machiningOrderClass::material_num_change($array['materialId'],$array['unit'],$unit,$array['num']);
        }
        return $num;
    }

}

